﻿using System;
using System.Web;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DB_QLSV;
using DB_QLSV.BusinessClassLibrary;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using System.Diagnostics;

namespace GUI_QLSV
{
    public partial class KhoaHoc : UserControl
    {
        public static List<StudentManagement.DataGVSubjectObject> subjectList = new List<StudentManagement.DataGVSubjectObject>();
        public static List<StudentManagement.DataGVSubjectObject> subjectListNull = new List<StudentManagement.DataGVSubjectObject>();
        public static TreeNode selectedNodeInBranch = new TreeNode();
        public static List<StudentManagement.DataGVSubjectObject> current_KhoaHocData_InGV = new List<StudentManagement.DataGVSubjectObject>();
        public KhoaHoc()
        {
            InitializeComponent();

            List<DB_QLSV.KhoaHoc> yearList = KhoaHocBUS.LayDanhSach();
            DB_QLSV.KhoaHoc _null = new DB_QLSV.KhoaHoc();
            //to load cbbKhoaHoc
            cbbKhoaHoc.Items.Add("");
            foreach (DB_QLSV.KhoaHoc item in yearList)
            {
                cbbKhoaHoc.Items.Add(item);
            }
            cbbKhoaHoc.DisplayMember = "nam";
            cbbKhoaHoc.ValueMember = "makh";
            //to load tree view of course 
            // init 
            initKhoaTreeView();
            initSubjectDataGV();
            List<StudentManagement.SearchButtonObject> lst = StudentManagement.MonHocClass.initButtonSearch();
            foreach (StudentManagement.SearchButtonObject item in lst)
            {
                cbbSearch.Items.Add(item);
            }
            cbbSearch.DisplayMember = "ten";
            cbbSearch.ValueMember = "id";
            cbbSearch.SelectedIndex = 0;
            
        }
        // init treeviewFaculty
        public void initKhoaTreeView()
        {
            try
            {
                treeViewFaculty.BeginUpdate();
                treeViewFaculty.Nodes.Clear();
                TreeNode treeNodeRoot = new TreeNode(ConstantString.KHOA);

                treeViewFaculty.ImageList = imageListIcon;
                treeNodeRoot.ImageIndex = 0;
                treeNodeRoot.SelectedImageIndex = 2;
                treeViewFaculty.SelectedImageIndex = 2;

                treeViewFaculty.Nodes.Add(treeNodeRoot);
                List<Khoa> khoaObjectList = KhoaBUS.LayDanhSach();
                foreach (Khoa item in khoaObjectList)
                {
                    TreeNode nodeChild = new TreeNode(item.tenkhoa);
                    nodeChild.Tag = item;
                    nodeChild.ImageIndex = 0;
                    nodeChild.SelectedImageIndex = 2;
                    treeNodeRoot.Nodes.Add(nodeChild);
                }
                treeViewFaculty.ExpandAll();
            }
            finally
            {
                treeViewFaculty.EndUpdate();
            }
        }
        //to init datagridviewsubject
        public void initSubjectDataGV()
        {
            dataGVSubject.ReadOnly = true;
            dataGVSubject.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dataGVSubject.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            
            DataGridViewCellStyle type = new DataGridViewCellStyle();
            type.Font = new System.Drawing.Font(dataGVSubject.Font, FontStyle.Bold);
            type.Font = new System.Drawing.Font(dataGVSubject.Font.FontFamily, 11);
            dataGVSubject.ColumnHeadersDefaultCellStyle = type;
            dataGVSubject.ColumnHeadersDefaultCellStyle.BackColor = Color.Navy;
            dataGVSubject.ColumnHeadersDefaultCellStyle.ForeColor = Color.White;
            dataGVSubject.CellBorderStyle = DataGridViewCellBorderStyle.Single;

            dataGVSubject.Columns[1].DefaultCellStyle.Font =new System.Drawing.Font(dataGVSubject.DefaultCellStyle.Font, FontStyle.Regular);
            dataGVSubject.MultiSelect = false;
            dataGVSubject.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dataGVSubject.DataSource = subjectListNull;
            current_KhoaHocData_InGV = subjectListNull;
            
            //dataGVSubject.GridColor = Color.Black;
        }
        //to init treeviewBranch
        public void initBranchTreeView(Khoa khoaOject)
        {
            try
            { 
                treeViewBranch.BeginUpdate();
                treeViewBranch.Nodes.Clear();
                TreeNode treeNodeRoot = new TreeNode(khoaOject.tenkhoa);

                treeViewBranch.ImageList = imageListIcon;
                treeNodeRoot.ImageIndex = 1;
                treeNodeRoot.SelectedImageIndex =0;
                treeViewBranch.SelectedImageIndex = 1;

                treeViewBranch.Nodes.Add(treeNodeRoot);
                List<Nganh> lstBranch = NganhBUS.LayDanhSach(khoaOject);
                if (lstBranch == null)
                {
                }
                else
                {
                    foreach (Nganh item in lstBranch)
                    {
                        TreeNode nodeChild = new TreeNode(item.tennganh);
                        nodeChild.Tag = item;
                        nodeChild.ImageIndex = 1;
                        nodeChild.SelectedImageIndex = 0;
                        treeNodeRoot.Nodes.Add(nodeChild);
                    }   
                }
                treeViewBranch.ExpandAll();
            }
            finally
            {
                treeViewBranch.EndUpdate();
            }
        }

        private void cbbKhoaHoc_SelectedIndexChanged(object sender, EventArgs e)
        {
           // selectedNodeInBranch = treeViewBranch.GetNodeAt(e.X, e.Y);
            if (selectedNodeInBranch != null)
            {
                Nganh branchObject = (Nganh)selectedNodeInBranch.Tag;
                DB_QLSV.KhoaHoc year = new DB_QLSV.KhoaHoc();
                string _year = cbbKhoaHoc.Text;
                if (_year != "")
                {
                    year = (DB_QLSV.KhoaHoc)cbbKhoaHoc.SelectedItem;
                }
                if (_year == "")
                    //  labelCheck.Text = year.nam.ToString();
                    subjectList = MonHocBUS.LayDanhSach(branchObject);
                else
                {
                    if (branchObject != null)
                    {
                        subjectList = MonHocBUS.LayDanhSach(branchObject, year);
                    }
                }

                if (subjectList == null)
                {
                    dataGVSubject.DataSource = subjectListNull;
                    current_KhoaHocData_InGV = subjectListNull;
                }
                else
                {
                    dataGVSubject.DataSource = subjectList;
                    current_KhoaHocData_InGV = subjectList;
                }
            }
        }

        private void treeViewFaculty_MouseClick(object sender, MouseEventArgs e)
        {
            dataGVSubject.DataSource = subjectListNull;
            current_KhoaHocData_InGV = subjectListNull;
            if (dataGVSubject.DataSource != subjectListNull && dataGVSubject.DataSource!=null)
                  deleteSubjectObject = (StudentManagement.DataGVSubjectObject)dataGVSubject.Rows[0].DataBoundItem;
            txtSearch.Text = "Tìm Kiếm";
            

            selectedNodeInBranch.Tag = null;
            subjectList = subjectListNull;
            TreeNode nodeSelected = treeViewFaculty.GetNodeAt(e.X, e.Y);
            if (nodeSelected != null && e.Button != MouseButtons.Right)
            {
                Khoa khoaObject = (Khoa)nodeSelected.Tag;
                if (khoaObject != null)
                {
                    initBranchTreeView(khoaObject);    
                }
            }     
        }
       
        private void treeViewBranch_MouseClick(object sender, MouseEventArgs e)
        {
            if (dataGVSubject.DataSource != subjectListNull && dataGVSubject.RowCount != 0)
                deleteSubjectObject = (StudentManagement.DataGVSubjectObject)dataGVSubject.Rows[0].DataBoundItem;
            selectedNodeInBranch = treeViewBranch.GetNodeAt(e.X, e.Y);
            txtSearch.Text = "Tìm Kiếm";
            if (e.Button != MouseButtons.Right && selectedNodeInBranch != null)
            {
                Nganh branchObject = (Nganh)selectedNodeInBranch.Tag;
                if (branchObject == null)
                    return;
                DB_QLSV.KhoaHoc year = new DB_QLSV.KhoaHoc ();
                string _year = cbbKhoaHoc.Text;
                if (_year != "")
                {
                    year = (DB_QLSV.KhoaHoc)cbbKhoaHoc.SelectedItem;
                }
                if (_year == "")
                    //  labelCheck.Text = year.nam.ToString();
                    subjectList = MonHocBUS.LayDanhSach(branchObject);
                else
                {
                    if (branchObject != null)
                    {
                        subjectList = MonHocBUS.LayDanhSach(branchObject, year);
                    }
                }
                if (subjectList == null)
                {
                    dataGVSubject.DataSource = subjectListNull;
                    current_KhoaHocData_InGV = subjectListNull;
                }
                else
                {
                    dataGVSubject.DataSource = subjectList;
                    current_KhoaHocData_InGV = subjectList;
                }
                
            }
        }
        private void txtSearch_TextChanged(object sender, EventArgs e)
        {
            string searchText = txtSearch.Text;
            int index = cbbSearch.SelectedIndex;       
           
            List<StudentManagement.DataGVSubjectObject> tmp = new List<StudentManagement.DataGVSubjectObject>();
            tmp = StudentManagement.MonHocClass.getAllSubject_DependOn_Search(subjectList, searchText, index);
           
            if (tmp == null)
            {
                dataGVSubject.DataSource = subjectListNull;
                current_KhoaHocData_InGV = subjectListNull;
            }
            else
            {
                dataGVSubject.DataSource = tmp;
                current_KhoaHocData_InGV = tmp;
            }
        }
        private void txtSearch_MouseClick(object sender, MouseEventArgs e)
        {
            txtSearch.Text = "";
        }
        private void cbbSearch_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtSearch.Text = "Tìm kiếm";
            if (subjectList == null)
            {
                dataGVSubject.DataSource = subjectListNull;
                current_KhoaHocData_InGV = subjectListNull;
            }
            else
            {
                dataGVSubject.DataSource = subjectList;
                current_KhoaHocData_InGV = subjectList;
            }
        }
        //print file pdf
        private void btnPrint_Click(object sender, EventArgs e)
        {
            //create folder PDFPrint
            String bin = Directory.GetCurrentDirectory();
            int index = bin.IndexOf("bin");
            int iIndex = bin.IndexOf("DemoQLSV");
            string tmp = bin.Substring(0, iIndex);
            string tmpImage = tmp + @"\DemoQLSV\images\02_calendar.png";
            tmp = tmp + @"DemoQLSV\GUI_QLSV\PrintPDF\make.bat";
            ProcessStartInfo p = new ProcessStartInfo(tmp);
            Process pro = new Process();
            pro.StartInfo = p;
            pro.Start();
            pro.WaitForExit();
            //create file pdf
            var doc = new Document();
            string path = @"C:\PDFPrint\";
            string name =  System.DateTime.Now.ToUniversalTime().ToString();
            // PDF14304010022011
            DateTime dt = DateTime.Now;
            string filename = "PDF_" + dt.Hour+dt.Minute+dt.Second+"_"+ dt.Day + dt.Month + dt.Year+".pdf";
            //show time GMT time when PDF created
            //set header [1] text [2] font stype
            Phrase phase = new Phrase(DateTime.UtcNow.ToString("dd-MM-yyyy HH:mm:ss") + " GMT", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.COURIER, 8));
            PdfWriter.GetInstance(doc, new FileStream(path + filename, FileMode.Create));
            BaseFont baseFont = BaseFont.CreateFont("C:\\WINDOWS\\Fonts\\arial.ttf", BaseFont.IDENTITY_H, true);
            doc.Open();

            iTextSharp.text.Image gif = iTextSharp.text.Image.GetInstance(tmpImage);
            gif.Alignment = iTextSharp.text.Image.LEFT_ALIGN;
            gif.ScalePercent(50f);
            doc.Add(gif);
            //to write data from dataGV into pdf file
            PdfPTable pdfHeader = new PdfPTable(2);
            pdfHeader.LockedWidth = true;
            pdfHeader.TotalWidth = 240f;
            float[] widths = new float[2];
            widths[0] = 90f;
            widths[1] = 130F;
            pdfHeader.SetWidths (widths);

            //pdf cell
            PdfPCell pdfCell = null;
            //add header of the pdf table
            // c.1. Add Header of the pdf table
           // Font fontTitle = new Font(baseFont, 20f, Element.ALIGN_LEFT, new Color(216, 37, 33));
            iTextSharp.text.Font fontTitle = new iTextSharp.text.Font(baseFont, 20f, Element.ALIGN_CENTER, new iTextSharp.text.BaseColor(216, 37, 33));

            iTextSharp.text.Font font1 = new iTextSharp.text.Font(baseFont, 10f);

            //pdfCell = new PdfPCell(new Phrase(new Chunk("Trường Đại Học Khoa Học Tự Nhiên Thành Phố Hồ Chí Minh ", font1)));
            //pdfCell.FixedHeight = 16f;
            //pdfCell.BorderWidth = 0;
            //pdfHeader.AddCell(pdfCell);

            pdfCell = new PdfPCell(new Phrase(new Chunk("MÔN HỌC",fontTitle)));
            pdfCell.HorizontalAlignment = Element.ALIGN_CENTER;
            pdfCell.Colspan = 2;
            pdfCell.FixedHeight = 40f;
            pdfCell.BorderWidth = 0;
          //  pdfCell.PaddingTop = -2f;
            pdfHeader.AddCell(pdfCell);

            // c.2. Add Header row
         
            // Row 1
            pdfCell = new PdfPCell(new Phrase(new Chunk("Ngành học", font1)));
            //PdfPCell.HorizontalAlignment = Element.ALIGN_LEFT;
            pdfCell.FixedHeight = 16f;
            pdfCell.BorderWidth = 0;
            pdfHeader.AddCell(pdfCell);

            Nganh branchObject = (Nganh)selectedNodeInBranch.Tag;
            if (branchObject == null)
            {
                return;
            }
            pdfCell = new PdfPCell(new Phrase(new Chunk(": " + branchObject.tennganh, font1)));
            pdfCell.BorderWidth = 0;
            pdfHeader.AddCell(pdfCell);
            string nowDay = DateTime.Now.Day.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Year.ToString();
            // Row 2
            pdfCell = new PdfPCell(new Phrase(new Chunk("Ngày print ", font1)));
            pdfCell.FixedHeight = 16f;
            pdfCell.BorderWidth = 0;
            pdfHeader.AddCell(pdfCell);

            pdfCell = new PdfPCell(new Phrase(new Chunk(": " + nowDay, font1)));
            pdfCell.BorderWidth = 0;
            pdfHeader.AddCell(pdfCell);


            // Row 3
            pdfCell = new PdfPCell(new Phrase(new Chunk("Giáo viên ", font1)));
            pdfCell.FixedHeight = 16f;
            pdfCell.BorderWidth = 0;
            pdfHeader.AddCell(pdfCell);

            // Row 4
            pdfCell = new PdfPCell(new Phrase(new Chunk(": " + "Nguyễn Văn A", font1)));
            pdfCell.FixedHeight = 16f;
            pdfCell.BorderWidth = 0;
            pdfHeader.AddCell(pdfCell);

            doc.Add(pdfHeader);

            // Add content of gridview
            //Craete instance of the pdf table and set the number of column in that table
            PdfPTable ptbGrid = new PdfPTable(4);
            //fix the absolute width of the table
            ptbGrid.LockedWidth = true;
            ptbGrid.SpacingBefore = 20f;
            ptbGrid.TotalWidth = doc.Right - doc.Left;
            ptbGrid.HorizontalAlignment = Element.ALIGN_RIGHT;
            widths = new float[4];
            widths[0] = 0.6F;
            widths[1] = 1.0F;
            widths[2] = 1.0F;
            widths[3] = 1.4F;
           
            ptbGrid.SetWidths(widths);

            pdfCell = null;
            BaseFont bf1 = BaseFont.CreateFont("C:\\WINDOWS\\Fonts\\arial.ttf", BaseFont.IDENTITY_H, true);
            iTextSharp.text.Font fontGrid = new iTextSharp.text.Font(baseFont, 8);

            //Add Header of the pdf table
            pdfCell = new PdfPCell(new Phrase(new Chunk("Mã Môn Học", fontGrid)));
            pdfCell.BackgroundColor = new iTextSharp.text.BaseColor(222, 222, 222);
            pdfCell.FixedHeight = 16f;
            pdfCell.PaddingTop = 3f;
            pdfCell.HorizontalAlignment = Element.ALIGN_CENTER;
            ptbGrid.AddCell(pdfCell);

            pdfCell = new PdfPCell(new Phrase(new Chunk("Tên Môn Học", fontGrid)));
            pdfCell.BackgroundColor = new iTextSharp.text.BaseColor(222, 222, 222);
            pdfCell.PaddingTop = 3f;
            pdfCell.HorizontalAlignment = Element.ALIGN_CENTER;
            ptbGrid.AddCell(pdfCell);

            pdfCell = new PdfPCell(new Phrase(new Chunk("Tên Ngành", fontGrid)));
            pdfCell.BackgroundColor = new iTextSharp.text.BaseColor(222, 222, 222);
            pdfCell.PaddingTop = 3f;
            pdfCell.HorizontalAlignment = Element.ALIGN_CENTER;
            ptbGrid.AddCell(pdfCell);

            pdfCell = new PdfPCell(new Phrase(new Chunk("Mô Tả", fontGrid)));
            pdfCell.BackgroundColor = new iTextSharp.text.BaseColor(222, 222, 222);
            pdfCell.PaddingTop = 3f;
            pdfCell.HorizontalAlignment = Element.ALIGN_CENTER;
            ptbGrid.AddCell(pdfCell);
            //  
            //How add the data from datatable to pdf table
            int i = 1;
            int iNumOfItem = 0;
            if (subjectList == null)
                return;
            foreach (StudentManagement.DataGVSubjectObject item in current_KhoaHocData_InGV)
            {
                //pdfCell = new PdfPCell(new Phrase(new Chunk(i++.ToString(), fontGrid)));
                //pdfCell.FixedHeight = 16f;
                //pdfCell.HorizontalAlignment = Element.ALIGN_CENTER;
                //pdfCell.PaddingTop = 3f;
                //ptbGrid.AddCell(pdfCell);
                
                pdfCell = new PdfPCell(new Phrase(new Chunk(item.mamonhoc, fontGrid)));
                pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
                pdfCell.PaddingTop = 3f;
                ptbGrid.AddCell(pdfCell);

                pdfCell = new PdfPCell(new Phrase(new Chunk(item.tenmonhoc, fontGrid)));
                pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
                pdfCell.PaddingTop = 3f;
                ptbGrid.AddCell(pdfCell);

                pdfCell = new PdfPCell(new Phrase(new Chunk(item.tennganh, fontGrid)));
                pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
                pdfCell.PaddingTop = 3f;
                ptbGrid.AddCell(pdfCell);

                pdfCell = new PdfPCell(new Phrase(new Chunk(item.mota, fontGrid)));
                pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
                pdfCell.PaddingTop = 3f;
                ptbGrid.AddCell(pdfCell);
            }

            doc.Add(ptbGrid);
            doc.Close();
            Process.Start(path + filename);
        }
        public static MonHoc subjectObject = new MonHoc();
        private void bttDelete_Click(object sender, EventArgs e)
        {
            if (subjectList != null && dataGVSubject.DataSource != subjectListNull)
            {
                if (deleteSubjectObject == null)
                {
                    deleteSubjectObject = (StudentManagement.DataGVSubjectObject)dataGVSubject.Rows[0].DataBoundItem;
                }
                DialogResult rs = MessageBox.Show("Bạn muốn xóa môn học " + deleteSubjectObject.tenmonhoc + " không ? ", "Hỏi", MessageBoxButtons.OKCancel,MessageBoxIcon.Question);
                if (rs == DialogResult.OK)
                {
                    MessageBox.Show("Môn học " + deleteSubjectObject.tenmonhoc + " đã được xóa ", "Kết quả xóa", MessageBoxButtons.OK);
                }
            }
            else
            {
                return;
            }
        }
        private void bttAdd_Click(object sender, EventArgs e)
        {
            frmThemMonHoc frm = new frmThemMonHoc();
            frm.Show();
        }
        public static  StudentManagement.DataGVSubjectObject deleteSubjectObject = new StudentManagement.DataGVSubjectObject();
        private void dataGVSubject_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            int row = e.RowIndex;
            if (row < 0)
                return;
            String rowDataGVSubject = dataGVSubject.Rows[row].Cells["mamonhoc"].Value.ToString();
          //  d = (StudentManagement.DataGVSubjectObject)dataGVSubject.SelectedRows[0].DataBoundItem;
            deleteSubjectObject = (StudentManagement.DataGVSubjectObject)dataGVSubject.Rows[row].DataBoundItem;
        }
    }
}
